package org.timemachine.listener;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.timemachine.Change;
import org.timemachine.action.facade.EntityChangeFacade;
import org.timemachine.action.facade.ForwardEntityChangeFacade;
import org.timemachine.factory.EntityChangeFactory;
import org.timemachine.factory.spi.EntityChange;
import org.timemachine.tool.ClassHelperImpl;
import org.timemachine.tool.spi.ClassHelper;

public class TimeMachineBaseListener {
	private Properties prop = new Properties();
	
	protected EntityChange getEntityChangeForEntity(Object entity) {
		return EntityChangeFactory.convertEntityChange(entity);
	}
	
	protected EntityChangeFacade findEntityChangeFacade() throws NamingException, IOException {
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/META-INF/timeMachineConfig.properties");
		String projectName="";
		if (inputStream != null) {
			prop.load(inputStream);
			projectName = prop.getProperty("project.name");
		}
		EntityChangeFacade facade= (EntityChangeFacade) new InitialContext().lookup("java:global/"+projectName+"/EntityChangeFacadeBean");
		return facade;
	}
	
	protected ForwardEntityChangeFacade findForwardEntityChangeFacade() throws NamingException, IOException {
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/META-INF/timeMachineConfig.properties");
		String projectName="";
		if (inputStream != null) {
			prop.load(inputStream);
			projectName = prop.getProperty("project.name");
		}
		ForwardEntityChangeFacade facade= (ForwardEntityChangeFacade) new InitialContext().lookup("java:global/"+projectName+"/ForwardEntityChangeFacadeBean");
		return facade;
	}
	
	protected boolean isEntityHasChangeAnno(Object entity) {
		ClassHelper classHelper = new ClassHelperImpl();
		
		Vector<Class<?>> clazzes = new Vector<Class<?>>();
		clazzes.add(entity.getClass());
		
		Set<Class<? extends Annotation>> annos = new HashSet<Class<? extends Annotation>>();
		annos.add(Change.class);
		
		Set<Class<?>> clazzesWithAnnotation = classHelper.findClassesWithAnnotation(clazzes, annos);
		
		if (clazzesWithAnnotation.size()>0 ) {
			return true;
		}
		return false;

	}
		
}
